<?php

namespace app\services;

use app\payment\PayFactory;
use plugin\admin\app\model\UserProperty;
use plugin\admin\app\model\UserPropertyLog;

class PropertyService
{

    public static function reduce($userId, $propertyType, $amount, $source, $remark = '', $orderNo = '')
    {
        $user = UserProperty::where('user_id', $userId)->first();

        if (! $user) {
            throw new \Exception('不存在的用户');
        }

        if (bcsub($user[$propertyType], $amount, 2) < 0) {
            throw new \Exception('资产不足');
        }

        UserProperty::where('user_id', $userId)->decrement($propertyType, $amount);

        UserPropertyLog::insert([
            'user_id' => $userId,
            'source' => $source,
            'type' => $propertyType,
            'before' => $user[$propertyType],
            'amount' => -$amount,
            'remark' => $remark,
            'order_no' => $orderNo,
            'created_time' => date('Y-m-d H:i:s')
        ]);
    }

    public static function add($userId, $propertyType, $amount, $source, $remark = '', $orderNo = '', $rewardType = 0)
    {
        $user = UserProperty::where('user_id', $userId)->first();

        if (! $user) {
            UserProperty::insert(['user_id' => $userId]);
        }

        UserProperty::where('user_id', $userId)->increment($propertyType, $amount);

        $data = [
            'user_id' => $userId,
            'source' => $source,
            'type' => $propertyType,
            'before' => $user[$propertyType],
            'amount' => $amount,
            'remark' => $remark,
            'order_no' => $orderNo,
            'created_time' => date('Y-m-d H:i:s')
        ];

        if ($rewardType) {
            $data['reward_type'] = $rewardType;
        }

        UserPropertyLog::insert($data);
    }
}